/**
 * Copyright (C), 2015-2022, 开度
 * FileName: JDBCUtil
 * Author:   ASUS
 * Date:     2022/6/27 17:44
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * Hezeyu           2022/6/27           1.0
 */
package com.example.spring.security.mysql.utils;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

/**
 * 〈〉
 *
 * @author Hezeyu
 * @create 2022/6/27
 * @since 1.0.0
 */
public class JDBCUtil {

    private static Properties prop = new Properties();
    static{
        InputStream in = null;
        try{

            in = JDBCUtil.class.getResourceAsStream("/jdbc.properties");
            prop.load(in);

            //1.加载驱动
            Class.forName(prop.getProperty("jdbc.driverClassName"));
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    private static ThreadLocal<Connection> tol = new ThreadLocal<Connection>();
    // 创建连接，并返回
    public static Connection getConn() {
        // 2.先到当前线程获取，如果没有说明是第一次调用工具类，那么创建一个新的，同时存入当前线程
        Connection conn = tol.get();
        try {
            if(conn == null){
                conn = DriverManager.getConnection(prop.getProperty("jdbc.url"),
                        prop.getProperty("jdbc.username"),
                        prop.getProperty("jdbc.password"));
                // 将创建的conn存入到当前线程中
                tol.set(conn);
            }

            return conn;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取连接失败！·");
        }
    }

    // 释放资源
    public static void close(ResultSet rs, Statement stm, Connection conn) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (stm != null) {
                stm.close();
            }
            if (conn != null) {
                conn.close();
                // 从当前线程移除关闭的连接
                tol.remove();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 释放资源
    public static void close(Statement stm, Connection conn) {
        try {
            if (stm != null) {
                stm.close();
            }
            if (conn != null) {
                conn.close();
                // 从当前线程移除关闭的连接
                tol.remove();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
